package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.service.MemberService;
import com.kly.user.constant.RedisKey;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.dao.UserPromotionRecordDao;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.enums.AppCodeEnum;
import com.kly.user.enums.AppEnum;
import com.kly.user.msgClient.MsgAPI;
import com.kly.user.service.AsyncSendMsgService;
import com.kly.user.utils.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 用户注册成功10s后消息通知
 */
@Component
public class MessageNoticeTask {

    private static Log logger = LogFactory.getLog(MessageNoticeTask.class);

    @Autowired
    RedisService redisService;

    @Resource
    private AsyncSendMsgService asyncSendMsgService;

    @Resource
    private MemberService memberService;

    @Resource
    private MsgAPI msgAPI;

    @Resource
    private UserPromotionRecordDao userPromotionRecordDao;

    @Resource
    private UserDao userDao;


    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

    @Scheduled(fixedDelay = 10000)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============MessageNoticeTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        //通过zset 进行实现 用户注册10s后发送消息
        Set<ZSetOperations.TypedTuple<Object>> objectSet = redisService.rangeByScoreWithScores(RedisKey.NEW_USER_LIST, 0, System.currentTimeMillis());
        objectSet.forEach(object -> {
            String userCode = (String) object.getValue();
            String message = "Hi,Ready for something extraordinary? \uD83D\uDE80Step into Meboo, where connections blossom! \uD83D\uDC96Now, you can start exploring our community, making new friends, and sharing your interests and hobbies.\n" +
                    "If you have any questions, you can refer to the platform's Q&A or reach out to our team anytime. We wish you a memorable time on our platform!\uD83D\uDE09\n" +
                    "Go check out the Q&A";
            UserEntity userEntity= userDao.selectByUserCode(userCode);
            if (userEntity == null) {
                return;
            }
            if (userEntity.getAppCode().equals(AppCodeEnum.PP.getAppCode())) {
                message = "Welcome to our social platform! ✨We're thrilled to have you join us\uD83D\uDC97Now, you can start exploring our community, making new friends, and sharing your interests and hobbies. \n\n" +
                        "If you have any questions or need assistance, please feel free to reach out to our team. We wish you a memorable time on our platform!\uD83D\uDE09";
            }
//            String sender = asyncSendMsgService.getSender(userEntity.getAppCode());
            asyncSendMsgService.sendMsg(userEntity.getAppCode(), userCode, "RC:InfoNtf", message, message);
            redisService.zRemove(RedisKey.NEW_USER_LIST, userCode);
        });

        //用户注册成功后，30min内没有付费
        Set<ZSetOperations.TypedTuple<Object>> thirtyLaterObjectSet = redisService.rangeByScoreWithScores(RedisKey.THIRTY_LATER_USER_LIST, 0, System.currentTimeMillis());
        thirtyLaterObjectSet.forEach(object -> {
            String userCode = (String) object.getValue();
            Response<Boolean> response = memberService.ifMember(userCode);
            if (response.isSuccess()) {
                Boolean ifMember = response.getData();
                logger.info("MessageNoticeTask:sendMsg-ifMember:{}, userCode;{}", ifMember, userCode);
                if (!ifMember) {
                    String message = "As a member, your prestigious status will earn you even more favor ✨";
                    UserEntity userEntity = userDao.selectByUserCode(userCode);
                    if (userEntity != null) {
                        asyncSendMsgService.sendMsg(userEntity.getAppCode(), userCode, "RC:InfoNtf", message, message);
                    }
                }
                redisService.zRemove(RedisKey.THIRTY_LATER_USER_LIST, userCode);
            }
        });

        Set<ZSetOperations.TypedTuple<Object>> discountMessageObjectSet = redisService.rangeByScoreWithScores(RedisKey.DISCOUNT_MESSAGE_USER_LIST, 0, System.currentTimeMillis());
        discountMessageObjectSet.forEach(object -> {
            String userCode = (String) object.getValue();
            int userPromotionCount = userPromotionRecordDao.getUserPromotionCount(userCode);
            logger.info("MessageNoticeTask:sendMsg-userPromotionCount:{} userCode;{}", userPromotionCount, userCode);
            if (userPromotionCount > 0) {
                String message = "Limited-time special offer of membership ends in 03:00,  click here to get limited-time special premium.";
                UserEntity userEntity = userDao.selectByUserCode(userCode);
                asyncSendMsgService.sendMsg(userEntity.getAppCode(), userCode, "RC:InfoNtf", message, message);
            }
            redisService.zRemove(RedisKey.DISCOUNT_MESSAGE_USER_LIST, userCode);
        });

        Set<ZSetOperations.TypedTuple<Object>> discountPushObjectSet = redisService.rangeByScoreWithScores(RedisKey.DISCOUNT_PUSH_USER_LIST, 0, System.currentTimeMillis());
        discountPushObjectSet.forEach(object -> {
            String value = (String) object.getValue();
            int userPromotionCount = userPromotionRecordDao.getUserPromotionCount(value);
            if (userPromotionCount > 0) {
                msgAPI.sendBackMessage(AppEnum.MEBOO, value, "Limited-time Special Premium", "The original price will be restored soon", "Get special now", 120);
            }
            redisService.zRemove(RedisKey.DISCOUNT_PUSH_USER_LIST, value);
        });
    }
}
